const jwt = require('jsonwebtoken');
const config = require('../../project.config');
const koaJwt = require('koa-jwt');

/** 从请求中获取token */
const getToken = (ctx) => {
  let { authorization } = ctx.header;
  return authorization.replace('Bearer ', '').replace('bearer ', '');
};

const verify = (token) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, config.JWT_SECRET, (err, payload) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(payload);
    });
  });
};

const middleware = (app) => {
  app.use(
    koaJwt({
      secret: config.JWT_SECRET,
    }).unless({
      path: [/^\/auth\/login/, /^\/auth\/register/],
    })
  );
};

const catchTokenError = (ctx, next) => {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = {
        msg: 'token校验失败',
        code: 0,
        data: null,
      };
    } else {
      throw err;
    }
  });
};

module.exports = {
  verify,
  getToken,
  middleware,
  catchTokenError,
};
